package com.play.ballen.network;

import com.play.ballen.event.EventCost;
import com.yuven.appframework.network.ExceptionHandle;
import com.yuven.baselib.component.eventbus.Event;
import com.yuven.baselib.component.eventbus.EventBusUtil;
import com.yuven.baselib.utils.GsonUtils;
import com.yuven.baselib.utils.Logger;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

public class BallenRxHelper {


    public static <T> ObservableTransformer<BaseResult<T>, T> transformResponse() {
        return new ObservableTransformer<BaseResult<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseResult<T>> upstream) {
                return upstream.flatMap(new Function<BaseResult<T>, Observable<T>>() {
                    @Override
                    public Observable<T> apply(BaseResult<T> tBaseResult) throws Exception {
                        Logger.i("RxHelper", "result from api : " + GsonUtils.toGson(tBaseResult));
                        return createData(tBaseResult);
                    }
                });
            }
        };
    }

    private static <T> Observable<T> createData(final BaseResult<T> data) {
        return Observable.create(subscriber -> {
            if (BallenResultCode.CODE_HTTP_OK.equals(data.getCode())) {
                 if(data.getData()!=null){
                     subscriber.onNext(data.getData());
                 }
            } else {
                if (BallenResultCode.CODE_TOKEN_FAILURE.equals(data.getCode()) || BallenResultCode.CODE_OTHER_DEVICE_LOGIN.equals(data.getCode())) {
                    EventBusUtil.post(Event.create(EventCost.CODE_LOGIN_STATUS_FAILURE));
                } else {
                    subscriber.onError(new ExceptionHandle.ServerException(data.getCode(), data.getMsg()));
                }
            }
            subscriber.onComplete();
        });
    }

    public static class HttpErrorHandleFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(Throwable throwable) throws Exception {
            return Observable.error(ExceptionHandle.handleException(throwable));
        }
    }

}
